//
//  ImageDownloader.m
//  Lesson_17_ImageDownloader
//
//  Created by lanou3g on 15-4-8.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ImageDownloader.h"

@implementation ImageDownloader
//button addTarget内部实现原理相同
+ (void)imageDownloaderWithURLStr:(NSString *)urlStr delagate:(id <ImageDownloaderDelegate>)delegate {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *image = [UIImage imageWithData:data];
        
        if (delegate != nil && [delegate respondsToSelector:@selector(imageDownloaderDidFinishDownloadImage:)]) {
            [delegate imageDownloaderDidFinishDownloadImage:image];
        }
    }];
}

+ (void)imageDownloaderWithURLStr:(NSString *)urlStr result:(Result)result {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *image = [UIImage imageWithData:data];
        result(image);
    }];
}

@end
